import { match, RoutingContext, createMemoryHistory } from 'dva/router';
import { renderToString } from 'react-dom/server'
import { routes } from '../isomorphism/router';
import createApp from '../isomorphism/createApp';
import config from './utils/config';
import createLoading from 'dva-loading';

export default function (req, res) {
  match({
    routes,
    location: req.url,
  }, (err, redirectLocation, renderProps) => {
    if (err) {
      res.status(500).end(`Internal Server Error ${err}`);
    }
    else if (redirectLocation) {
      res.redirect(302, redirectLocation.pathname + redirectLocation.search);
    } else if (renderProps) {
      const other = createApp({
        history: createMemoryHistory(),
      }, true);
      const otherhtml = renderToString(other.start()({ renderProps }));
      const loginuser = req.session.user || {};
      const loginstate = req.session.user ? true : false;
      res.end(renderFullPage(otherhtml, { staticServer: config.staticServer, sessionid: req.session.id, userinfo: loginuser, islogin: loginstate }));
    } else {
      res.status(404).send('Not found');
    }
  });
}

function renderFullPage(html, initialState) {
  return `
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <link rel="stylesheet" href="${config.staticServer}style.css?v=${config.version}" />
  <link rel="stylesheet" href="${config.staticServer}antd.min.css" />
</head>
<body>
  <div id="root" class='root-box'>
    <div>
      ${html}
    </div>
  </div>
  <script>
    window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
  </script>
  <script src="/static/vendor.bundle.js?v=${config.version}"></script>
  <script src="/static/index.bundle.js?v=${config.version}"></script>
</body>
</html>
  `;
}

